package com.k.liuzh.extraffic.Database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private final static String DATABASE_NAME = "tranffic.db";
    private final static int databaseVersion = 2;
    private static DatabaseHelper instance;

    private Map<String,Dao> daos = new HashMap<>();
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, databaseVersion);
    }

    public static synchronized DatabaseHelper getInstance(Context context) {
        if(instance == null){
            synchronized (DatabaseHelper.class){
                if (instance == null){
                    instance = new DatabaseHelper(context);
                }
            }
        }
        return instance;
    }

    public synchronized Dao getDao(Class clazz) throws SQLException {
        Dao dao = null;
        String className = clazz.getSimpleName();
        if(daos.containsKey(className)){
            dao = daos.get(className);
        }
        if(dao == null) {
            dao = super.getDao(clazz);
            daos.put(className,dao);
        }

        return  dao;
    }


    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource,ChongZhiBean.class);
            TableUtils.createTable(connectionSource,EnvironmentBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            TableUtils.dropTable(connectionSource,ChongZhiBean.class,true);
            TableUtils.dropTable(connectionSource,EnvironmentBean.class,true);
            onCreate(database,connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void close() {
        // TODO Auto-generated method stub
        super.close();
        for(String key : daos.keySet()){
            Dao dao = daos.get(key);
            dao = null;
        }
    }
}
